<?php
/*由bean脚本生成 powerBy--joe*/

namespace app\common\manage;

use app\common\bean\CategoryGroupBean;
use app\common\bean\DistributionBean;
use app\common\bean\GlobalBean;
use app\common\bean\OrderGoodsDetailBean;
use app\common\bean\OrderTotalBean;
use app\common\bean\StoreBean;
use app\common\bean\UserAddressBean;
use app\common\bean\UserBean;
use app\common\enum\CategoryGroupTypeEnum;
use app\common\enum\ContentTypeEnum;
use app\common\enum\OrderGoodsPayTypeEnum;
use app\common\enum\OrderGoodsStatusEnum;
use app\common\enum\OrderTotalTypeEnum;
use app\common\model\DistributionModel;
use app\common\model\OrderGoodsDetailModel;
use app\common\model\OrderTotalModel;
use app\common\model\StoreModel;
use app\common\model\StoreUserModel;
use app\common\model\UserModel;
use app\common\utils\CommonUtil;
use app\common\utils\CurlUtil;
use app\common\utils\ExitJsonUtil;
use app\common\validate\OrderGoodsValidate;
use app\common\model\OrderGoodsModel;
use app\common\bean\OrderGoodsBean;
use app\common\bean\ListMap;
use app\common\utils\TimeUtil;
use app\common\exception\MyException;
use Exception;
use think\Db;

class OrderGoodsManage extends BaseManage
{
    /**
     * @return OrderGoodsManage
     */
    static function getInstance() {
        return parent::getInstance();
    }

    public function payBack(OrderGoodsBean $orderGoodsBean) {
        $this->callBack($orderGoodsBean, OrderGoodsPayTypeEnum::WXPAY, $orderGoodsBean->getParameter('blance'));
    }

    public function pay(ListMap $listMap) {
        $orderGoodsBean = new OrderGoodsBean();
        $orderGoodsBean->setId($listMap->getParameter('id'));
        $order = $this->getInfo($orderGoodsBean);
        if ($order->getStatus() != OrderGoodsStatusEnum::NOPAY)
            ExitJsonUtil::getInstance()->exitData($order->getData(), 301, "该订单已经支付");

        if ($listMap->getParameter('pay_type') == OrderGoodsPayTypeEnum::WXPAY) {
            $data['out_trade_no'] = $orderGoodsBean->getOrderNumber();
            $data['total_fee'] = $orderGoodsBean->getRealPrice();
            $data['body'] = '照相馆消费';
            $data['tag'] = '相册';
            $data['notify_url'] = request()->domain().'/api/Order/callBack';
            $data['openid'] = $listMap->getParameter('openid');
            return CommonUtil::getInstance()->weixinPay($data);
        } elseif ($listMap->getParameter('pay_type') == OrderGoodsPayTypeEnum::BLANCE) {
            $user = UserManage::getInstance()->reduceBlance($listMap->getParameter('uid'), $order->getRealPrice());
            $this->callBack($orderGoodsBean, OrderGoodsPayTypeEnum::BLANCE, $user->getBlance());
            return [];
        }

    }

    private function callBack(OrderGoodsBean $orderGoodsBean, $payType, $blance) {
        $storeBean = new StoreBean();
        $storeBean->setId($orderGoodsBean->getStoreId());
        $store = StoreManage::getInstance()->getInfo($storeBean);
        $storeBlance = $orderGoodsBean->getRealPrice()*(1-($store->getRate()/1000));
        StoreModel::getInstance()->where([StoreBean::$id=>$store->getId()])->setInc(StoreBean::$blance, $storeBlance);
        $data[OrderGoodsBean::$payTime] = time();
        $data[OrderGoodsBean::$status] = OrderGoodsStatusEnum::HADPAY;
        $data[OrderGoodsBean::$payType] = $payType;
        OrderGoodsModel::getInstance()->updatedData([OrderGoodsBean::$id=>$orderGoodsBean->getId()], $data);

        $tdata[OrderTotalBean::$orderNumber] = $orderGoodsBean->getOrderNumber();
        $tdata[OrderTotalBean::$userId] = $orderGoodsBean->getUserId();
        $tdata[OrderTotalBean::$type] = OrderTotalTypeEnum::CONS;
        $tdata[OrderTotalBean::$transactionPrice] = $orderGoodsBean->getRealPrice();
        $tdata[OrderTotalBean::$blance] = $blance;
        $tdata[OrderTotalBean::$createdAt] = date('Y-m-d H:i:s');
        OrderTotalModel::getInstance()->insert( $tdata );

        $uwhere[UserBean::$id] = $orderGoodsBean->getUserId();
        UserModel::getInstance()->where( $uwhere )->setInc(UserBean::$integral, $orderGoodsBean->getTotalPrice());
        UserModel::getInstance()->where( $uwhere )->setInc(UserBean::$amont, $orderGoodsBean->getTotalPrice());
        UserModel::getInstance()->where( $uwhere )->setInc(UserBean::$orderNum);

        $paytypes = ['', '微信支付', '余额支付'];
        $mess_data = [
            'first'=>['value'=>'您有新的订单'],
            'keyword1'=>['value'=>$orderGoodsBean->getRealPrice().'元'],
            'keyword2'=>['value'=>'支付方式：'.$paytypes[$payType]],
            'keyword3'=>['value'=>$orderGoodsBean->getOrderNumber()],
            'keyword4'=>['value'=>'用户'],
        ];
        $su = StoreUserModel::getInstance()->selectData(['store_id'=>$orderGoodsBean->getStoreId()]);
        CurlUtil::getInstance()->templateMess($su['public_open_id'], '9Af_uC3pbQJ1MCHe97jRG7ycoswyg0REUkZ_Qv1v0mI', $mess_data);
    }

    public function create(ListMap $listMap) {
        $cids = $listMap->getParameter('cids');
        $uid = $listMap->getParameter(OrderGoodsBean::$userId);
        if (!$row = CategoryGroupManage::getInstance()->singleRow( $cids )) {
            ExitJsonUtil::getInstance()->exitData([], 200, '属性不能为空');
        }
        if($row[CategoryGroupBean::$type]==CategoryGroupTypeEnum::CERPHOTO && !$listMap->getParameter(OrderGoodsBean::$remark)){
            ExitJsonUtil::getInstance()->exitData([], 200, '必须填写备注');
        }
        $price = CategoryGroupManage::getInstance()->getPrice($uid, $cids);
        if($price==0){
            ExitJsonUtil::getInstance()->exitData([], 505, '该商品无法下单');
        }
        $postage = $this->calPostage($listMap->getParameter('user_address_id'), $row[CategoryGroupBean::$storeId]);

        $obj = json_decode($listMap->getParameter('obj'), true);
        $suffix = pathinfo($obj[0]['url'], PATHINFO_EXTENSION);
        $file_type = in_array($suffix, ['jpg', 'jpeg', 'png']) ? 1 : 2;
        $total_num = 0;
        $total_price = 0;
        foreach ($obj as $o) {
            $total_num += $o['num'];
            $pages = $file_type==1 ? 1 : count_pages(substr($o['url'], 1));
            $order_detail[] = [
                OrderGoodsDetailBean::$url => json_encode(array($o['url'])),
                OrderGoodsDetailBean::$filePage => $pages,
                OrderGoodsDetailBean::$fileCount => $o['num'],
                OrderGoodsDetailBean::$goodsPrice => number_format($o['num']*$pages*$price,1),
                OrderGoodsDetailBean::$createdAt => TimeUtil::getInstance()->getTimeNow()
            ];
            $total_price += $o['num']*$pages*$price;
        }

        $orderGoodsBean = new OrderGoodsBean();
        $orderGoodsBean->setOrderNumber(CommonUtil::getInstance()->getUnique('order'));
        $orderGoodsBean->setStoreId($row[CategoryGroupBean::$storeId]);
        $orderGoodsBean->setUserId( $uid );
        $orderGoodsBean->setType($row[CategoryGroupBean::$type]);
        $orderGoodsBean->setCategoryGroupId($row[CategoryGroupBean::$id]);
        $orderGoodsBean->setCategoryGroupPrice($price);
        $orderGoodsBean->setCategoryGroupName(CategoryManage::getInstance()->getCateName($row[CategoryGroupBean::$categoryIds]));
        $orderGoodsBean->setGoodsCount($total_num);
        $orderGoodsBean->setTotalPrice($total_price);
        $orderGoodsBean->setRealPrice($total_price + $postage);
        $orderGoodsBean->setCreatedAt(date('Y-m-d H:i:s'));
        $orderGoodsBean->setPostage($postage);
        $orderGoodsBean->setUserAddressId($listMap->getParameter(OrderGoodsBean::$userAddressId));
        $orderGoodsBean->setRemark($listMap->getParameter(OrderGoodsBean::$remark));
        $orderGoodsBean->setPhone( $listMap->getParameter(OrderGoodsBean::$phone) );
        $orderGoodsBean->setFileType($file_type);
        $oid = $this->add($orderGoodsBean);

        foreach ($order_detail as &$o) {
            $o[OrderGoodsDetailBean::$orderGoodsId] = $oid;
        }
        OrderGoodsDetailModel::getInstance()->insertAll($order_detail);
        $orderGoodsBean = new OrderGoodsBean();
        $orderGoodsBean->setId($oid);
        $orderGoodsBean = $this->getInfo($orderGoodsBean);
        return $orderGoodsBean;
    }

    /**
     * 根据订单id分包
     * $oid 订单id
     */
    public function getSplit( $oid ){
        $count = Db::name('order_goods_detail')->where(['order_goods_id'=>$oid])->count();
        $number = ceil($count/10);
        for($i=0;$i<$number;$i++){
            $sarr[] = $i+1==$number ? [$i*10+1,$count] : [$i*10+1,$i*10+10];
        }
        return $sarr;
    }
    public function downZip(OrderGoodsBean $orderGoodsBean, $start=1) {
        $end = $start+9;
        $dname = str_replace("/", "_", $orderGoodsBean->getOrderNumber()."-{$orderGoodsBean->getCategoryGroupName()}-{$start}-{$end}");
        $zip_url = $dname.'.zip';
        if(!is_file($zip_url)){
            deleteZip();
            @mkdir($dname, 0777);
            chmod($dname, 0777);
            $zip = new \ZipArchive();
            $zip->open($zip_url, \ZipArchive::CREATE);
            $y = 0;
            foreach ($orderGoodsBean->getData()->order_details as $d) {
                $y++;
                if($y>=$start){
                    $name = "编号{$y}洗{$d[OrderGoodsDetailBean::$fileCount]}张";
                    $suffix = strrchr($d['domain_url'], '.');
                    $newurl = "{$dname}/{$name}$suffix";
                    $url = str_replace('_thumb', '', $d['domain_url']);
                    copy($url, $newurl);
                    $zip->addFile($newurl);
                }
                if( $y>=$start+9 ) break;
            }
            $zip->close();
            deleteDir($dname);
        }
        return request()->domain()."/".$zip_url;
    }

    public function detail(OrderGoodsBean $orderGoodsBean) {//获取订单详情的列表
        $where[OrderGoodsDetailBean::$orderGoodsId] = $orderGoodsBean->getId();
        return OrderGoodsDetailModel::getInstance()->selectData($where, true);
    }

    /**
     * @desc 根据主建获取数据
     * @param OrderGoodsBean $orderGoodsBean
     * @return OrderGoodsBean $orderGoodsBean
     * @throws Exception
     **/
    //public function getInfo1($orderGoodsBean) {
    //    $result = OrderGoodsModel::getInstance()->selectData([OrderGoodsBean::$id => $orderGoodsBean->getId()]);
    //    $result ?: MyException::throwMyException("获取信息失败");
    //    $orderGoodsBean->setData($result);
    //    return $orderGoodsBean;
    //}

    /**
     * @desc 根据主建获取数据
     * @param OrderGoodsBean $orderGoodsBean
     * @return OrderGoodsBean $orderGoodsBean
     * @throws Exception
     **/
    public function getInfo($orderGoodsBean) {
        //OrderGoodsValidate::getInstance()->goCheck(OrderGoodsValidate::$pkId,$orderGoodsBean->getData());
        $sotre_id = $orderGoodsBean->getParameter(OrderGoodsBean::$storeId);
        if ($sotre_id != 0) $where[$orderGoodsBean::$storeId] = $sotre_id;
        $where[OrderGoodsBean::$id] = $orderGoodsBean->getId();
        $result = OrderGoodsModel::getInstance()->selectData($where, false, '', ['userAddress', 'orderDetails']);
        $result ?: MyException::throwMyException("获取信息失败");
        $orderGoodsBean->setData($result);
        return $orderGoodsBean;
    }

    /**
     * @desc 获取分页数据
     * @param ListMap $listMap
     * @return ListMap $listMap
     * @throws Exception
     **/
    public function getDetail(ListMap $listMap) {
        $conditionMap = new ListMap();
        $conditionMap->setData($listMap->getData());
        $conditionMap->setField(ALL_FIELD);
        $conditionMap->setWith(['withdetail']);
        $conditionMap->setOrder(OrderGoodsBean::$createdAt." desc");
        //自行选择是连表查询还是单表查询,默认单表
        $resultMap = OrderGoodsModel::getInstance()->getList($conditionMap);
        $resultMap ?: MyException::throwMyException("查询数据失败");
        return $resultMap;
    }

    /**
     * @desc 获取分页数据
     * @param ListMap $listMap
     * @return ListMap $listMap
     * @throws Exception
     **/
    public function getPaginatorList(ListMap $listMap) {
        $conditionMap = new ListMap();
        if ($timeArray = TimeUtil::getInstance()->dealBetweenTime($listMap))
            $conditionMap->setParameter(OrderGoodsBean::$alias.POINST.OrderGoodsBean::$createdAt, $timeArray);
        $conditionMap->setAlias(OrderGoodsBean::$alias);
        $listMap->setField(OrderGoodsBean::$alias.ALL_FIELD);
        $conditionMap->setParameter(OrderGoodsBean::$status, $listMap->getParameter(OrderGoodsBean::$status));
        $conditionMap->setParameter(OrderGoodsBean::$userId, $listMap->getParameter('uid'));
        $conditionMap->setOrder(OrderGoodsBean::$id.' DESC');
        !$this->getParamBool($listMap, "orderFieldName") ?: $conditionMap->setOrder($listMap->getParameter('orderFieldName').SPACE.$listMap->getParameter('orderType'));
        $sotre_id = $listMap->getParameter(OrderGoodsBean::$storeId);
        if ($sotre_id == 0) {
            $with = ['withstore', 'withuser'];
        } else {
            $with = ['withuser'];
            $conditionMap->setParameter(OrderGoodsBean::$storeId, $sotre_id);
        }
        $conditionMap->setWith($with);


        //自行选择是连表查询还是单表查询,默认单表
        $resultMap = OrderGoodsModel::getInstance()->getList($conditionMap);
        $resultMap ?: MyException::throwMyException("查询数据失败");
        return $resultMap;
    }

    /**
     * @desc 添加数据
     * @param OrderGoodsBean $orderGoodsBean
     * @return int int
     * @throws Exception
     **/
    public function add($orderGoodsBean) {
        OrderGoodsValidate::getInstance()->goCheck(OrderGoodsValidate::$add, $orderGoodsBean->getData());
        // Todo:添加业务处理代码...


        $orderGoodsBean->setCreatedAt(TimeUtil::getInstance()->getTimeNow());
        $result = OrderGoodsModel::getInstance()->addDataGetInsertId($orderGoodsBean->getData());
        $result ?: MyException::throwMyException("插入数据失败");
        return $result;
    }

    /**
     * @desc 编辑数据
     * @param OrderGoodsBean $orderGoodsBean
     * @return int int
     * @throws Exception
     **/
    public function edit($orderGoodsBean) {
        // Todo:添加业务处理代码...
        $result = OrderGoodsModel::getInstance()->updatedData([OrderGoodsBean::$id => $orderGoodsBean->getId()], $orderGoodsBean->getData());
        $result ?: MyException::throwMyException("更新失败");
        return $result;
    }

    /**
     * @desc 删除数据
     * @param OrderGoodsBean $orderGoodsBean
     * @return int int
     * @throws Exception
     **/
    public function delete($orderGoodsBean) {
        OrderGoodsValidate::getInstance()->goCheck(OrderGoodsValidate::$pkId, $orderGoodsBean->getData());
        // Todo:添加业务处理代码...


        $result = OrderGoodsModel::getInstance()->deleteData([OrderGoodsBean::$id => $orderGoodsBean->getId()]);
        $result ?: MyException::throwMyException("删除失败");
        return $result;
    }

    /**
     * 运费计算
     * @param $uai      int 地址id 0自提
     * @param $store_id int
     * @return  运费
     * @throws Exception
     */
    public function calPostage($uai, $store_id) {
        if ($uai != 0) {
            $userAddressBean = new UserAddressBean();
            $userAddressBean->setId($uai);
            $address = UserAddressManage::getInstance()->getInfo($userAddressBean);

            $storeBean = new StoreBean();
            $storeBean->setId($store_id);
            $store = StoreManage::getInstance()->getInfo($storeBean);
            $distance = GetDistance($address->getDetailLat(), $address->getDetailLng(), $store->getContactAddrLat(), $store->getContactAddrLng());
            $dis = DistributionModel::getInstance()->selectData([DistributionBean::$storeId => $store_id], true, DistributionBean::$distance.' ASC');
            foreach ($dis as $d) {
                if ($distance >= $d[DistributionBean::$distance]) {
                    $postage = $d[DistributionBean::$price];
                } else {
                    return $d[DistributionBean::$price];
                }
            }
            return $postage;
        }
        return 0;
    }

    /**
     * 计算商品列表的价格
     * @param ListMap $listMap
     */
    public function getOrderDetailPrices(ListMap $listMap) {
        $orderDetailPrices = array();
        $price = CategoryGroupManage::getInstance()->getPrice($listMap->getParameter(OrderGoodsBean::$userId), $listMap->getParameter('cids'));
        foreach (json_decode($listMap->getParameter("goodList"),true) as &$item){
            $url = json_decode($item['pic'])[0];
            $suffix = pathinfo($url, PATHINFO_EXTENSION);
            $isimg = in_array($suffix, ['jpg', 'jpeg', 'png']) ? true : false;
            $ismsg = in_array($suffix, ['pdf', 'docx', 'doc','jpg', 'jpeg', 'png']) ? false : true;
            $pages = $isimg ? 1 : count_pages(substr($url, 1));
            $item['file_page'] = $pages*$item['num'];
            $item['goods_price'] = number_format($item['num']*$price*$pages,2);
            $orderDetailPrices[] = $item;
        }
        return [$orderDetailPrices, $ismsg];
    }
}
